<template>
  <div>
    <van-nav-bar
      title="购物车"
    />
    <div v-show="items.length===0" class="empty-cart">
      购物车空空如也！去逛逛吧！
    </div>
    <!--    整个购物车的商品div-->
    <div class="cart-all">
      <van-checkbox-group class="card-goods" v-model="checkedItems" v-on:change="changeSelect">
        <!--      单个商品的div-->
        <van-checkbox
          class="card-goods__item"
          v-for="item in items"
          :key="item.product.id"
          :name="item.product.id"
        >
          <!--        商品中的卡片-->
          <van-card
            :title="item.product.title"
            :desc="item.product.desc"
            :price="formatPrice(item.product.price)"
            :thumb="item.product.thumb"
          >
          <!----------------           --------->
<!--          <div class="van-card">-->
<!--            <div class="van-card__header">-->
<!--              <a class="van-card__thumb">-->
<!--                <img :src="item.product.thumb" class="van-card__img">-->
<!--              </a>-->
<!--              <div class="van-card__content">-->
<!--                <div class="van-card__title">{{item.product.title}}</div>-->
<!--                <div class="van-card__desc van-ellipsis">{{item.product.desc}}</div>-->
<!--                <div class="van-card__bottom">-->
<!--                  <div class="van-card__price">¥ {{formatPrice(item.product.price)}}</div>-->
<!--                  <div class="van-card__num">-->
<!--                    <div><del>原价：{{formatPrice(item.product.price)}}</del><div class="van-stepper">-->
<!--                      <van-stepper v-model="value" />-->
<!--                    </div>-->
<!--                    </div>-->
<!--                  </div>-->
<!--                </div>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->



          <!----------------           --------->
            <div slot="num">
              <del>原价：399</del>
              <van-stepper :min="0" v-model="item.quantity" v-on:change="changeStepper(item, item.product.id)" v-on:click.native.stop=""/>
            </div>
          </van-card>
        </van-checkbox>
      </van-checkbox-group>
    </div>

    <!--    下面的提交订单-->
    <van-submit-bar
      style="bottom: 50px"
      :price="totalPrice"
      :disabled="!checkedItems.length"
      :button-text="submitBarText"
      @submit="onSubmit"
    >
      <van-checkbox style="padding: 0 10px;" v-model="checkedAllFlag" @change="toggleSetCheckAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import { Checkbox, CheckboxGroup, Card, SubmitBar, NavBar, Stepper, Toast } from 'vant'
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'

export default {
  components: {
    [Card.name]: Card,
    [Checkbox.name]: Checkbox,
    [SubmitBar.name]: SubmitBar,
    [CheckboxGroup.name]: CheckboxGroup,
    [NavBar.name]: NavBar,
    [Stepper.name]: Stepper
  },
  data () {
    return {
      checkedItems: [],
      checkedAllFlag: false
    }
  },
  async mounted () {
    this.setActiveTab(2)
    console.log(this.items)
    const ids = this.items.map(item => item.product.id)
    if (ids.length > 0) {
      console.log('refreshCart')
      await this.refreshCart({ ids: ids })
    }
    this.checkedItems = [...this.checkedItemsState]
  },
  computed: {
    ...mapState({
      items: state => state.cart.items,
      checkoutStatus: state => state.cart.checkoutStatus
    }),
    ...mapGetters('cart', {
      totalPrice: 'totalPrice',
      checkedItemsState: 'checkedItems'
    }),
    submitBarText () {
      const count = this.checkedItems.length
      return '结算' + (count ? `(${count})` : '')
    }
  },
  methods: {
    ...mapMutations({
      setActiveTab: 'tabbar/setActiveTab',
      toggleCheckedAll: 'cart/toggleCheckedAll',
      changeSelected: 'cart/changeSelected',
      deleteProductFromCart: 'cart/deleteProductFromCart'
    }),
    ...mapActions({
      refreshCart: 'cart/refreshCart'
    }),
    toggleSetCheckAll () {
      console.log('select all')
      this.toggleCheckedAll()
      if (this.checkedAllFlag) {
        this.checkedItems = this.items.map(item => item.product.id)
      } else {
        this.checkedItems = []
      }
    },
    changeSelect (selected) {
      this.changeSelected(selected)
    },
    checkout (products) {
      this.$store.dispatch('cart/checkout', products)
    },
    formatPrice (price) {
      return (price).toFixed(2)
    },
    changeStepper (item, productId) {
      if (item.quantity === 0) {
        this.$dialog.confirm({
          title: '删除',
          message: '从购物车中删除该商品？'
        }).then(() => {
          this.deleteProductFromCart(productId)
          this.checkedItems = this.checkedItems.filter(item => item !== productId)
        }).catch(() => {
          item.quantity = item.quantity + 1
        })
      }
    },
    async onSubmit () {
      // create order and route to payment page
      let source = this.$route.query.source || 0
      let sourceId = this.$route.query.source_id || 0
      // const details = this.items.filter(item => item.checked).map(item => { return { 'product': item.product.id, quantity: item.quantity } })
      const checkedDetails = this.items.filter(item => item.checked)
      var details = []
      for (let i = 0; i < checkedDetails.length; i++) {
        const item = checkedDetails[i]
        if (item.quantity > 1) {
          for (let i = 0; i < item.quantity; i++) {
            details.push({ 'product': item.product.id, quantity: 1 })
          }
        } else {
          details.push({ 'product': item.product.id, quantity: 1 })
        }
      }
      console.log(details)
      const params = {
        'source': source,
        'source_id': sourceId,
        'remark': '',
        'order_details': details
      }
      const { data } = await this.$api.order.orderCreate(params)
      if (data.code !== 200) {
        Toast(data.desc)
        this.$store.commit('cart/setCheckoutStatus', 'failed')
      } else {
        this.$store.commit('cart/setCheckoutStatus', 'successful')
        const remainItems = [...this.items].filter(item => !item.checked)
        this.$store.commit('cart/setCartItems', { items: remainItems })
        this.$router.replace({ name: 'payment', params: { id: data.data.id } })
      }
    }
  }
}
</script>

<style lang="less">
  .cart-all{
    width: 100%;
    height: 100%;
    /*background-color: #ebedf030;*/
  }
  .empty-cart {
    text-align: center;
    margin-top: 50px;
  }
  .card-goods {
    padding: 10px 0;
    /*整体定义了一个背景颜色这列就不用定义了*/
    /*background-color: #fff;*/
    /*单个商品块的div 宽度百分百 占一整行*/
    &__item {
      /*设置和边缘的距离 外边框要是灰色的 商品栏是白色的*/
      border-radius: 10px;
      margin: 0 10px 10px 10px;
      position: relative;
      background-color: white;
      /*左边包含拖那一块*/
      .van-card__thumb{
        width: 80px;
        height: 80px;
      }
      /*商品图片的样式*/
      .van-card__thumb img {
        /*van-card定义了padding 这里就不用单独定义了*/
        /*margin-top: 10px;*/
        border: 0;
        width: 70px;
        height: 70px;
        border-radius: 10px;
      }
      /*商品标题*/
      .van-card__title{
        font-size: 14px;
        /*设置多出部分不会被隐藏/*/
        overflow: visible;
      }
      /*商品描述*/
      .van-card__desc {
        overflow: visible;
      }
      .van-checkbox__label {
        width: 100%;
        height: auto; // temp
        padding: 0 10px 0 15px;
        box-sizing: border-box;
      }
      .van-checkbox__icon {
        top: 50%;
        left: 10px;
        z-index: 1;
        position: absolute;
        margin-top: -10px;
      }
      .van-card__price {
        /*font-size: 15px;*/
        width: 25%;
        margin-top: 5px;
        color: #f44;
      }
      /*van-card中自定义的样式背景颜色是灰色的 要重写样式把它改过来*/
      .van-card{
        background-color: white;
        /*定义图片和商品描述距离整个外框的距离*/
        padding: 10px 10px 0 10px;
        margin: 5px;
        box-shadow: 0 0 0 0 white;
      }

      /*重写右下角的计数器和原价*/
      /*.card-goods__item */
      .van-card__num {
        /*父元素使用相对定位 等等对原价进行绝对定位让他在父元素限制范围内的底部！ */
        position: relative;
        height: auto;
        width: 75%;
        margin-top: 3px;
        /*padding-top: 15px;*/
        /*width: 65%;*/
        float: right;
        /*原价*/
        del{
          position: absolute;
          bottom: 0;
          /*margin: 20px 10px 0 0;*/
          font-family: "Hiragino Sans GB", arial, "Microsoft Yahei", sans-serif;
          font-size: 11px;
          color: rgb(139, 139, 139);
          margin-left: 0;
          /*float: left;*/
        }
        .van-stepper {
          /*width: 150px;*/
          /*margin-bottom: 10px;*/
          float: right;
          /*调整计数器的大小*/
          .van-stepper__minus {
            width: 18px;
            height: 18px;
          }
          .van-stepper__input {
            width: 20px;
            height: 20px;
            padding: 0;
          }
          .van-stepper__plus {
            width: 18px;
            height: 18px;
          }

        }

      }

    }
  }
</style>
